var OrderTransferForm = function () {
  var Material = function (order) {
    BaseModel.call(this);

    var self = this;
    var changeFields = ['materialName', 'model', 'color', 'providerName'];
    var formFields = ['materialCode', 'materialName', 'model', 'providerName', 'color', 'colorDescription', 'materialType', 'defaultWarehouse',
      'procurementCycles', 'transmittance', 'material', 'count',
    ];

    var fn = {
      initData: function (order) {
        self.initObject(formFields);
        self.procurementCycles = undefined;
        self.defaultWarehouse = "1";
        self.materialDept = '';

        var unitPrice = order.unitPrice;
        if (SysUtil.isEmpty(unitPrice)) {
          unitPrice = undefined;
        }
        self.unitPrice = unitPrice;
        self.unit = '付';

        self.orderId = order.orderId;
        self.rowIndexs = order.rowIndex;
      }
    };

    this.saveOldData = function () {
      this.setOldData(changeFields);
    };

    this.getSearchObject = function () {
      var postData = {
        color: this.color
      };
      var changeFields = ['materialName', 'model', 'providerName'];
      for (var i = 0; i < changeFields.length; i++) {
        var field = changeFields[i];
        var value = this[field];
        if (SysUtil.isEmpty(value)) {
          return null;
        }
        postData[field] = value;
      }
      return postData;
    };

    this.resetObject = function (data) {
      var fields = ['materialCode', 'unit', 'material', 'unitPrice', 'procurementCycles', 'materialType'];
      this.setDataFromObj(data, fields);

      var defaultWarehouse = data.defaultWarehouse;
      defaultWarehouse = i18n.getKeyByValue('spotMaterial.defaultWarehouse', defaultWarehouse);
      this.defaultWarehouse = defaultWarehouse;
    };

    this.resetMainData = function (data) {
      this.setDataFromObj(data, changeFields);
      this.materialDept = data.materialDept;
      this.materialType = data.materialType;
    };

    this.checkValid = function () {
      var fields = ['materialName', 'model', 'providerName', 'defaultWarehouse', 'materialType', 'unit'];
      return CheckVaildUtil.checkNullField(fields, this);
    };

    this.getObject = function (canUpdate, outWarehouseInfo) {
      var postData = {
        type: 1,
        otherOrderId: this.orderId,
        customerName: this.providerName,
        inOutUnit: this.unit,
        inCountPrice: 0,
        outCount: outWarehouseInfo.count,
        remark: outWarehouseInfo.remark,
        materialName: '',
        model: '',
        providerName: ''
      };

      var fields = ['orderId', 'rowIndexs'];
      this.setPostData(postData, fields);

      if (canUpdate) {
        postData.materialCode = '';
        postData.isEquals = this.unit === '付' ? 1 : 0;
        postData.status = "使用";
        postData.isStock = 1;

        var materialFields = ['materialName', 'materialType', 'model', 'color', 'colorDescription', 'providerName',
          'unit', 'unitPrice', 'procurementCycles', 'material'
        ];
        if (this.materialType === '镜片') {
          materialFields.push('transmittance');
        }
        this.setPostData(postData, materialFields, true, true);

        var defaultWarehouse = this.defaultWarehouse;
        defaultWarehouse = i18n.getMsg('spotMaterial.defaultWarehouse.' + defaultWarehouse);
        postData.defaultWarehouse = defaultWarehouse;

        var materialDept = this.materialDept;
        if (materialDept !== '') {
          postData.materialDeptId = materialDept.materialDeptId;
        }
      } else {
        postData.materialCode = this.materialCode;
      }
      return postData;
    };

    fn.initData(order);
  };

  var template = /* html */ `
    <div class="order-transfer-form" v-loading.fullscreen.lock="loading">
      <div class="from-info" v-if="material!==null">
        <div class="transfer-form-item">
          <div class="form-title">成品信息</div>
          <div class="form-item-content">
            <el-form class="order-info-from" label-width="auto">
              <el-form-item label="系统订单编号">
                <span>{{order.orderId}}</span>
              </el-form-item>
              <el-form-item label="订单编号">
                <span>{{order.companyOrderId}}</span>
              </el-form-item>
              <el-form-item label="工厂型号">
                <span>{{order.factoryNo}}</span>
              </el-form-item>
              <el-form-item label="客户型号">
                <span>{{order.customerNo}}</span>
              </el-form-item>
              <el-form-item label="订单序号">
                <span>{{order.rowIndex}}</span>
              </el-form-item>
              <el-form-item label="合格数">
                <span>{{order.count}}</span>
              </el-form-item>
              <el-form-item label="不合格数">
                <span>{{order.noCount}}</span>
              </el-form-item>

              <template v-if="order.hasProduction">
                <el-form-item label="生成单位合格数">
                  <span>{{order.productionUnitCount}}</span>
                </el-form-item>
                <el-form-item label="生成单位不合格数">
                  <span>{{order.productionUnitNoCount}}</span>
                </el-form-item>
              </template>
            </el-form>
          </div>
        </div>
        <div class="transfer-form-item">
          <div class="form-title">物料信息</div>
          <div class="form-item-content">
            <el-form label-width="115px">
              <el-form-item required label="物料名称">
                <sys-autocomplete v-if="isUpdateMaterialName" class="form-input" v-model="material.materialName" :options="materialNameList"
                  @change="searchMaterial()">
                </sys-autocomplete>
                <span v-else>{{material.materialName}}</span>
              </el-form-item>
              <el-form-item required label="规格型号">
                <sys-autocomplete class="form-input" v-model="material.model" :options="modelList" @change="searchMaterial()">
                </sys-autocomplete>
              </el-form-item>
              <el-form-item label="编号">
                <sys-autocomplete class="form-input" v-model="material.color" :options="colorList" @change="searchMaterial()">
                </sys-autocomplete>
              </el-form-item>
              <el-form-item required label="供应商">
                <el-select filterable class="form-input" v-model="material.providerName" @change="searchMaterial()">
                  <el-option v-for="providerName in providerNameList" :key="providerName" :value="providerName">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="描述">
                <el-input class="form-input" v-model="material.colorDescription"></el-input>
              </el-form-item>
              <el-form-item label="物料部门">
                <el-select clearable filterable class="form-input" v-model="material.materialDept" value-key="materialDeptId" @change="deptChange">
                  <el-option v-for="dept in deptList" :key="dept.materialDeptId" :value="dept" :label="dept.materialDeptName">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item required label="默认仓库">
                <el-select v-if="canUpdate" class="form-input" v-model="material.defaultWarehouse">
                  <el-option v-for="warehouse in warehouseList" :key="'warehouse_'+warehouse.value" :value="warehouse.value"
                    :label="warehouse.label"></el-option>
                </el-select>
                <span v-else>{{i18n.getMsg('spotMaterial.defaultWarehouse.'+material.defaultWarehouse)}}</span>
              </el-form-item>
              <el-form-item required label="物料类型">
                <el-select v-if="canUpdate" filterable class="form-input" v-model="material.materialType" @change="resetMaterialName()">
                  <el-option v-for="materialType in materialTypeList" :key="'materialType_'+materialType" :value="materialType"></el-option>
                </el-select>
                <span v-else>{{material.materialType}}</span>
              </el-form-item>
              <el-form-item label="材质">
                <el-input v-if="canUpdate" class="form-input" v-model="material.material"></el-input>
                <span v-else>{{material.material}}</span>
              </el-form-item>
              <el-form-item v-if="material.materialType==='镜片'" label="透光率(%)">
                <el-input-number v-if="canUpdate" class="form-input" v-model="material.transmittance" controls-position="right" :min="0" :max="100" :precision="0">
                </el-input-number>
                <span v-else>{{material.transmittance}}</span>
              </el-form-item>
              <el-form-item required label="单位">
                <el-select v-if="canUpdate" filterable class="form-input" v-model="material.unit">
                  <el-option v-for="(unit,index) in unitList" :key="'unit_'+index" :value="unit">
                  </el-option>
                </el-select>
                <span v-else>{{material.unit}}</span>
              </el-form-item>
              <el-form-item label="单价">
                <el-input-number v-if="canUpdate" class="form-input" v-model="material.unitPrice" controls-position="right" :min="0" :precision="2">
                </el-input-number>
                <span v-else>{{material.unitPrice}}</span>
              </el-form-item>
              <el-form-item label="计价单位是否和生产单位相同" class="equal-form-input">
                <span>{{material.unit==='付'?'相同':'不相同'}}</span>
              </el-form-item>
              <el-form-item label="采购周期">
                <el-input-number v-if="canUpdate" class="form-input" v-model="material.procurementCycles" controls-position="right" :min="0" :precision="0">
                </el-input-number>
                <span v-else>{{material.procurementCycles}}</span>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="transfer-form-item out-warehouse-form" style="border-top:1px solid #cccccc;">
          <el-form label-width="auto">
            <el-form-item required label="转仓数量">
              <el-input-number is-decimal-zero class="form-input" v-model="outWarehouseInfo.count" controls-position="right" :min="1/Math.pow(10,countPrecision)"
                :precision="countPrecision"></el-input-number>
            </el-form-item>
            <el-form-item label="备注">
              <el-input class="form-input" v-model="outWarehouseInfo.remark" type="textarea" :autosize="{minRows:1}" resize="none" @keydown.native.enter.prevent></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div style="text-align:center;margin-top:10px;">
          <el-button size="medium" type="primary" @click="ensure(false)">成品转仓</el-button>
          <el-button :disabled="!hasApproval" size="medium" type="primary" @click="ensure(true)">审核过账</el-button>
        </div>
      </div>
      <div class="from-table">
        <query-material-table @select-row="selectMaterial"></query-material-table>
      </div>
    </div>
  `;

  return {
    mixins: [
      materialFormMixin('material')
    ],

    props: {
      order: {
        type: Object,
        required: true
      },

      dropdownOption: {
        type: Object,
        default: function () {
          return {};
        }
      }
    },

    watch: {
      "material.defaultWarehouse": function () {
        this.warehouseChange();
      },

      materialLoading: function (val) {
        if (!val && this.toSave) {
          this.ensure(this.isAduit);
        }
      }
    },

    computed: {
      countPrecision: function () {
        var unit = this.material.unit;
        return SysUtil.getMaterialNumberPrecision(unit, 4);
      }
    },

    data: function () {
      return {
        loading: false,
        materialLoading: false,
        toSave: false,
        material: new Material(this.order),
        outWarehouseInfo: {
          count: undefined,
          remark: ''
        },
        hasApproval: false,
        materialNameList: [],
        modelList: [],
        colorList: [],
        providerNameList: [],
        deptList: [],
        warehouseList: i18n.getDropDown('spotMaterial.defaultWarehouse', ['1', '2']),
        materialTypeList: [],
        unitList: [],
        isUpdateMaterialName: true,
        canUpdate: true,
        isAduit: null
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      return Promise.all([
        this.checkApprovalPermission(),
        this.setDropdownList('materialNameList'),
        this.setDropdownList('modelList'),
        this.setDropdownList('colorList'),
        this.setDropdownList('providerNameList', 'customerName'),
        this.setDeptList(),
        this.setMaterialTypeList(),
        this.setDropdownList('unitList')
      ]).then(function () {
        var providerNameList = self.providerNameList;
        if (providerNameList.indexOf('本厂加工') !== -1) {
          self.material.providerName = '本厂加工';
        }

        self.resetMaterialName(true);
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      checkApprovalPermission: function () {
        var self = this;
        return PermissionUtil.ajaxCheckPermission(6).then(function (hasApproval) {
          self.hasApproval = hasApproval;
          return hasApproval;
        });
      },

      setMaterialData: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          var material = self.material;
          var unit = user.companyInfo.type === 1 ? '付' : '';
          material.unit = unit;
          return material;
        });
      },

      setDropdownList: function (field, dataField) {
        var dropdownList = this.dropdownOption[field];
        if (dropdownList !== undefined) {
          this[field] = dropdownList;
          return Promise.resolve(dropdownList);
        }

        var url;
        var postData = {};
        switch (field) {
          case 'materialNameList':
            url = 'basicData/getCompanyMaterialName';
            break;
          case 'modelList':
            url = 'basicData/getCompanyModel';
            break;
          case 'colorList':
            url = 'basicData/getCompanyColor';
            break;
          case 'providerNameList':
            url = 'basicData/getCustomerName';
            postData = {
              view: 1
            };
            break;
          case 'unitList':
            url = 'basicData/getCompanyUnit';
        }

        var self = this;
        return ajaxRequest(url, postData).then(function (dropdownList) {
          var dropdownData = [];
          for (var i = 0; i < dropdownList.length; i++) {
            var dropdown = dropdownList[i];
            var value = dataField ? dropdown[dataField] : dropdown;
            if (!SysUtil.isEmpty(value)) {
              dropdownData.push(value);
            }
          }
          dropdownData = _.uniq(dropdownData);
          if (field === 'unitList') {
            dropdownData = _.orderBy(dropdownData, [function (value) {
              if (['条', '付'].indexOf(value) !== -1) {
                return 0;
              }
              return 1;
            }], ['asc']);
          }
          self[field] = dropdownData;
          self.dropdownOption[field] = dropdownData;
          return dropdownData;
        });
      },

      setDeptList: function () {
        var deptList = this.dropdownOption.deptList;
        if (deptList !== undefined) {
          this.deptList = deptList;
          return Promise.resolve(deptList);
        }

        var self = this;
        return ajaxRequest('basicData/getDeptName', {
          view: 1
        }).then(function (deptList) {
          deptList = _.map(deptList, function (dept) {
            return {
              materialDeptId: dept.id,
              materialDeptName: dept.deptName
            };
          });
          self.deptList = deptList;
          self.dropdownOption.deptList = deptList;
          return deptList;
        });
      },

      setMaterialTypeList: function () {
        var material = this.material;
        var self = this;
        return ajaxRequest("basicData/getRowMaterialType", {
          defaultWarehouse: material.defaultWarehouse
        }).then(function (materialTypeList) {
          self.materialTypeList = materialTypeList;
          return materialTypeList;
        });
      },

      warehouseChange: function () {
        this.loading = true;
        var self = this;
        this.setMaterialTypeList().then(function (materialTypeList) {
          var material = self.material;
          if (material.materialType !== '' && materialTypeList.indexOf(material.materialType) === -1) {
            material.materialType = '';
          }
          self.resetMaterialName(true);
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      searchMaterial: function (hasCheck) {
        var material = this.material;
        if (hasCheck) {
          if (material.materialName === material.getOldData('materialName')) {
            return;
          }
        }

        material.saveOldData();
        var postData = material.getSearchObject();
        if (postData === null) {
          this.canUpdate = true;
          return;
        }

        this.resetMaterialData(postData);
      },

      resetMaterialData: function (postData) {
        var self = this;
        this.materialLoading = true;
        return ajaxRequest('basicData/getCompanyMaterialListByDetail', postData).then(function (materialList) {
          for (var i = 0; i < materialList.length; i++) {
            var material = materialList[i];
            var materialDeptId = material.materialDeptId;
            var materialDeptName = material.materialDeptName;
            if (SysUtil.isEmpty(materialDeptId) || SysUtil.isEmpty(materialDeptName)) {
              material.materialDeptId = '';
              material.materialDeptName = '';
            }
          }

          var data = self.getBillMaterialDetail(materialList);
          self.resetMaterialObj(data);

          self.materialList = materialList;
          self.materialLoading = false;
        }).catch(function () {
          self.materialLoading = false;
        });
      },

      getBillMaterialDetail: function (materialList) {
        if (materialList === undefined) {
          materialList = this.materialList;
        }

        if (materialList.length === 0) {
          return null;
        }

        var materialDept = this.material.materialDept;
        var materialDeptId = materialDept === '' ? '' : materialDept.materialDeptId;
        var billMaterial = _.find(materialList, {
          materialDeptId: materialDeptId
        });
        if (billMaterial === undefined) {
          return null;
        }
        return _.cloneDeep(billMaterial);
      },

      deptChange: function () {
        var data = this.getBillMaterialDetail();
        this.resetMaterialObj(data);
      },

      resetMaterialObj: function (data) {
        var material = this.material;
        if (SysUtil.isEmpty(data)) {
          material.materialCode = '';
          this.canUpdate = true;
        } else {
          material.resetObject(data);
          this.canUpdate = false;
        }
      },

      selectMaterial: function (data) {
        var material = this.material;
        material.resetMainData(data);
        this.resetMaterialName();
        this.searchMaterial();
      },

      ensure: function (isAduit) {
        if (this.materialLoading) {
          this.toSave = true;
          this.isAduit = isAduit;
          return;
        }
        this.toSave = false;
        this.toTransferForm(isAduit);
      },

      toTransferForm: function (isAduit) {
        var material = this.material;
        var code = material.checkValid();
        if (code !== '') {
          var msg = i18n.getMsg('orderMaterialTransfer.error.' + code);
          this.$alert(msg, '信息');
          return;
        }

        var outWarehouseInfo = this.outWarehouseInfo;
        if (outWarehouseInfo.count === undefined) {
          var msg = i18n.getMsg('orderMaterialTransfer.error.count');
          this.$alert(msg, '信息');
          return;
        }

        var postData = material.getObject(this.canUpdate, outWarehouseInfo);
        postData.isAduit = isAduit;
        this.loading = true;
        var self = this;
        ajaxRequest('warehouse/finishedProductToMaterial', postData).then(function () {
          self.isAduit = null;
          self.loading = false;
          self.$alert('成品转仓成功', '信息', {
            callback: function () {
              self.$emit('transfer-success');
            }
          });
        }).catch(function () {
          self.isAduit = null;
          self.loading = false;
        });
      }
    },

    components: {
      SysAutocomplete: SysAutocomplete,
      QueryMaterialTable: QueryMaterialTable
    },

    template: template
  };
}();
